package cn.tedu.lucky.draw.server.service.impl;

import cn.tedu.lucky.draw.server.common.enums.DrawEnum;
import cn.tedu.lucky.draw.server.common.enums.ErrorEnum;
import cn.tedu.lucky.draw.server.common.handler.DrawException;
import cn.tedu.lucky.draw.server.protocol.po.ActivityRule;
import cn.tedu.lucky.draw.server.protocol.po.Rule;
import cn.tedu.lucky.draw.server.repository.ActivityRuleRepository;
import cn.tedu.lucky.draw.server.repository.RuleRepository;
import cn.tedu.lucky.draw.server.service.IActivityRuleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivityRuleServiceImpl implements IActivityRuleService {

    private static final Logger log= LoggerFactory.getLogger(ActivityRuleServiceImpl.class);

    @Autowired
    private ActivityRuleRepository activityRuleRepository;

    @Autowired
    private RuleRepository ruleRepository;

    @Override
    public List<Rule> findRuleByActivityId(Long id) {
        List<ActivityRule> activityRules = activityRuleRepository.findByActivityId(id);
        log.info("activityRules={}", activityRules);
        List<Long> ruleIds = activityRules.stream().map(ActivityRule::getRuleId).collect(Collectors.toList());
        List<Rule> rules = ruleRepository.findAllById(ruleIds);
        log.info("rules={}", rules);
        return rules;
    }

    @Override
    public List<Rule> findNoBindRuleByActivityId(Long id) {
        List<ActivityRule> activityRuleList = activityRuleRepository.findByActivityId(id);
        List<Long> excludedIds = activityRuleList.stream().map(ActivityRule::getRuleId).collect(Collectors.toList());
        Integer status = Integer.valueOf(DrawEnum.ENABLE.getCode());
        if (excludedIds.isEmpty()) {
            return ruleRepository.findByStatus(status);
        }
        return ruleRepository.findByStatusAndIdNotIn(status, excludedIds);
    }

    @Override
    public void saveAll(List<ActivityRule> activityRules) {
        List<ActivityRule> activityRuleList = activityRuleRepository.saveAll(activityRules);
        if(activityRuleList==null){
            throw new DrawException(ErrorEnum.SYSTEM_ERROR);
        }
    }
}
